import happybase

connection = happybase.Connection('192.168.32.102',port=9090)

table_name = 'students'


if table_name.encode() not in connection.tables():
    connection.create_table(table_name, {'info': dict()})



def add_student_info(student_id, name, age):
    table = connection.table(table_name)
    table.put(student_id, {'info:name': name, 'info:age': age})

def update_student_info(student_id,name=None,age=None):
    table = connection.table(table_name)
    if name:
        table.put(student_id, {'info:name': name})
    if age:
        table.put(student_id, {'info:age': age})

def get_student_info(student_id):

    table = connection.table(table_name)
    row = table.row(student_id)
    if row:
        name = row[b'info:name'].decode()
        age = row[b'info:age'].decode()
        return {'name': name,'age': age}
    else:
        return None


def scan_student_info():
    table=connection.table(table_name)
    scanner=table.scan()
    students=[]
    for key, data in scanner:
        student_id=key.decode()
        name=data[b'info:name'].decode()
        age=data[b'info:age'].decode()
        students.append({'student_id': student_id, 'name': name, 'age': age})
    return students


add_student_info('20223016017', 'yuyang', '20')

add_student_info('002', 'Bob', '21')

print(get_student_info('001'))
print(get_student_info('002'))

update_student_info('001', age='21')

print(get_student_info('001'))

students = scan_student_info()
for student in students:
    print(student)

connection.close()